package com.sgb.kjwl.view.ui.fragment.transport.company;

import android.graphics.Color;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragCargoManageBinding;
import com.sgb.kjwl.model.entity.transport.LinkedEntity;
import com.sgb.kjwl.model.entity.transport.MotorcadListEntity;
import com.sgb.kjwl.view.constant.RouterKey;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.self.GoodsManageEvent;
import com.sgb.kjwl.view.ui.activity.transport.company.AffiliatedFleetDetailsActivity;
import com.sgb.kjwl.view.ui.adapter.self.logistics.LinkedItemAdapter;
import com.sgb.kjwl.viewmodel.transport.LinkItemModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.util.ArrayUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: 熊丽
 * @date: 2021/10/9 10:59
 * @Description: 车队列表内容页
 */
public class ProprietaryAndLinkItemFragment extends AppLazyFragment {
    LinkItemModel viewModel;
    FragCargoManageBinding binding;
    //货源列表
    private List<MotorcadListEntity> mList;
    private LinkedItemAdapter mAdapter;
    //
    private boolean mIsGeneralGoods;
    private int mPattern;
    private int mState;
    private int mPage = 1;

    public static ProprietaryAndLinkItemFragment newInstance(int state, boolean isLinked) {
        ProprietaryAndLinkItemFragment fragment = new ProprietaryAndLinkItemFragment();
        Bundle args = new Bundle();
        args.putInt(RouterKey.TYPE, state);
        args.putBoolean(RouterKey.BOOLEAN, isLinked);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        viewModel = new ViewModelProvider(this).get(LinkItemModel.class);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.frag_cargo_manage, container, false);
        binding.setLifecycleOwner(this);
        return binding.getRoot();
    }

    @Override
    protected void onLazyLoad() {
        initIntentParams();
        initRecycler();
        initEvent();
        initData();
    }

    private void initIntentParams() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            mState = getArguments().getInt(RouterKey.TYPE);
            mIsGeneralGoods = getArguments().getBoolean(RouterKey.BOOLEAN, true);
            mPattern = mIsGeneralGoods ? 0 : 1;
        }
    }

    private void initRecycler() {
        mList = new ArrayList<>();
        mAdapter = new LinkedItemAdapter(mList);
        binding.rvCargoManage.setLayoutManager(new LinearLayoutManager(getActivity()));
        if (getActivity() != null) {
            DividerDecoration.builder(getActivity())
                    .showFirstDivider()
                    .color(Color.TRANSPARENT)
                    .size(10, TypedValue.COMPLEX_UNIT_DIP)
                    .build()
                    .addTo(binding.rvCargoManage);
        }
        mAdapter.bindToRecyclerView(binding.rvCargoManage);
    }

    private void initEvent() {

        binding.srlCargoManage.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                viewModel.getLinkItemList(getContext(), mPage, mState,2);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshData();
            }
        });
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            MotorcadListEntity info = mList.get(position);
            itemClick(view, info);
        });
        //接口回调
        viewModel.ldLinked.observe(this, this::refreshUIByData);
    }

    private void initData() {
        refreshData();
    }

    public void refreshData() {
        if (mAdapter != null) {
            mPage = 1;
            viewModel.getLinkItemList(getContext(), mPage, mState,2);
        }
    }

    /**
     * 删除提示
     */
    private void showDelDialog(MotorcadListEntity data) {
        new RoundDialog.Builder(getActivity())
                .title("温馨提示")
                .content("您确定要删除"+data.getMotorcadeName()+"车队吗？")
                .confirmCallback(v -> viewModel.deleteNo(getContext(), data.getNo()))
                .show();
    }

    /**
     * 解除挂靠提醒
     * @param data
     */
    private void relation(MotorcadListEntity data) {
        new RoundDialog.Builder(getActivity())
                .title("温馨提示")
                .content("挂靠解除后，该挂靠车队共享的司机和车辆将同时被取消共享。您确定要解除挂靠吗？")
                .confirmCallback(v -> viewModel.relation(getContext(), data.getNo()))
                .show();
    }

    /**
     * 同步数据
     */
    private void refreshUIByData(LinkedEntity listResponse) {
        binding.srlCargoManage.finishRefresh();
        binding.srlCargoManage.finishLoadMore();
        if (listResponse == null) {
            return;
        }
        //设置数据
        if (listResponse.getVo().getPageNumber() == 1) {
            mList.clear();
        }
        if (listResponse.getVo().getList() != null) {
            for (int i = 0;i<listResponse.getVo().getList().size();i++){
                listResponse.getVo().getList().get(i).setType(2);
            }
            mList.addAll(listResponse.getVo().getList());
        }
        if (ArrayUtil.isNullOrEmpty(mList)) {
            mAdapter.setEmptyView(R.layout.layout_null_list_logistics);
        }
        mAdapter.notifyDataSetChanged();

        //更新页码
        if (listResponse.getVo().getPageNumber() < listResponse.getVo().getPageSize()) {
                mPage = listResponse.getVo().getPageNumber() + 1;
                binding.srlCargoManage.setNoMoreData(false);
        } else {
            binding.srlCargoManage.finishLoadMoreWithNoMoreData();
        }
        EventBus.getDefault().post(GoodsManageEvent.make(EventConstant.EVENT_REFRESH_CARGO_MANAGE_TAB_COUNT, listResponse.getInviteNum()));

    }
    /**
     * 列表按钮点击事件
     */
    private void itemClick(View view, MotorcadListEntity info) {
        if (view.getId() == R.id.tv_item_fleet_edit) {
            relation(info);
        } else if (view.getId() == R.id.tv_item_fleet_del ) {
            showDelDialog(info);
        }else if (view.getId() == R.id.cl_fleet_item){
            AffiliatedFleetDetailsActivity.start(getContext(),false,info.getMotorcadeNo());
        }
    }

}
